package com.ruoyi.web.controller.system.fuw;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.LogUtils;
import com.ruoyi.fuw.domain.FuwComm;
import com.ruoyi.fuw.domain.FuwCommsOrders;
import com.ruoyi.fuw.domain.FuwOrder;
import com.ruoyi.fuw.service.IFuwCommService;
import com.ruoyi.fuw.service.IFuwCommsOrdersService;
import com.ruoyi.fuw.service.IFuwOrderService;
import com.ruoyi.web.controller.util.DataUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.fuw.domain.FuwCar;
import com.ruoyi.fuw.service.IFuwCarService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 购物车Controller
 * 
 * @author ruoyi
 * @date 2021-10-09
 */
@RestController
@RequestMapping("/fuw/car")
public class FuwCarController extends BaseController
{
    @Autowired
    private IFuwCarService fuwCarService;

    @Autowired
    private IFuwCommService fuwCommService;

    @Autowired
    private IFuwOrderService fuwOrderService;

    @Autowired
    private IFuwCommsOrdersService fuwCommsOrdersService;

    /**
     * 信息权限判断
     */
    @PreAuthorize("@ss.hasPermi('fuw:car:list')")
    public List<FuwCar> adminByCar()
    {
        List<FuwCar> list;
        // 判断是否是超级管理员，否则只能看到自己的信息
        if(getUsername().equals("admin")){
            list = fuwCarService.selectFuwCarList(null);
        }else{
            FuwCar fuwCar = new FuwCar();
            fuwCar.setPersonId(getUsername());
            list = fuwCarService.selectFuwCarList(fuwCar);
        }

        return list;
    }

    /**
     * 查询购物车列表
     */
    @PreAuthorize("@ss.hasPermi('fuw:car:list')")
    @GetMapping("/list")
    public TableDataInfo list(FuwCar fuwCar)
    {
        startPage();
        List<FuwCar> list = new ArrayList<>();
        // 判断是否是超级管理员，否则只能看到自己的购物车
        if (!getUsername().equals("admin")) {
            fuwCar.setPersonId(getUsername());
        }
        list = fuwCarService.selectFuwCarList(fuwCar);

        return getDataTable(list);
    }

    /**
     * 查询购物车中的用户下拉信息
     */
    @PreAuthorize("@ss.hasPermi('fuw:car:list')")
    @GetMapping("/list/personId")
    public AjaxResult listPersonId()
    {
        List<FuwCar> list = this.adminByCar();

        // list
        List<Map<String,Object>> listMap = new ArrayList<Map<String,Object>>();

        // 验证数据的map
        Map<String, Object> map = new HashMap<>();
        for(FuwCar fuwCarNow: list){
            if(map.get(fuwCarNow.getPersonId()) == null){
                map.put(fuwCarNow.getPersonId(), fuwCarNow.getPersonId());

                Map<String, Object> mapNew = new HashMap<>();
                mapNew.put("value", fuwCarNow.getPersonId());
                mapNew.put("label", fuwCarNow.getPersonId());
                listMap.add(mapNew);
            }
        }
        System.out.println("listMap =" + listMap.toString());

        return AjaxResult.success(listMap);
    }

    /**
     * 查询购物车中的商品下拉信息
     */
    @PreAuthorize("@ss.hasPermi('fuw:car:list')")
    @GetMapping("/list/commId")
    public AjaxResult listCommId()
    {
        List<FuwCar> list = this.adminByCar();

        // list
        List<Map<String,Object>> listMap = new ArrayList<Map<String,Object>>();

        // 验证数据的map
        Map<String, Object> map = new HashMap<>();
        for(FuwCar fuwCarNow: list){
            if(map.get(fuwCarNow.getCommId()) == null){
                map.put(fuwCarNow.getCommId(), fuwCarNow.getCommId());

                Map<String, Object> mapNew = new HashMap<>();
                mapNew.put("value", fuwCarNow.getCommId());
                mapNew.put("label", fuwCarNow.getCommId());
                listMap.add(mapNew);
            }
        }

        return AjaxResult.success(listMap);
    }

    /**
     * 导出购物车列表
     */
    @PreAuthorize("@ss.hasPermi('fuw:car:export')")
    @Log(title = "购物车", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(FuwCar fuwCar)
    {
        List<FuwCar> list = fuwCarService.selectFuwCarList(fuwCar);
        ExcelUtil<FuwCar> util = new ExcelUtil<FuwCar>(FuwCar.class);
        return util.exportExcel(list, "购物车数据");
    }

    /**
     * 获取购物车详细信息
     */
    @PreAuthorize("@ss.hasPermi('fuw:car:query')")
    @GetMapping(value = "/{uId}")
    public AjaxResult getInfo(@PathVariable("uId") Long uId)
    {
        return AjaxResult.success(fuwCarService.selectFuwCarByUId(uId));
    }

    /**
     * 商品加入购物车
     */
    @PreAuthorize("@ss.hasPermi('fuw:car:addCar')")
    @Log(title = "购物车", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FuwCar fuwCar)
    {
        System.out.println("fuwCar.getCommId() =" + fuwCar.getCommId());
        System.out.println("getUsername =" + getUsername());

        // 获取当前登录用户编号
        String username = getUsername();

        // 查询当前用户的购物车中是否存在改商品信息
        List<FuwCar> fuwCarList = fuwCarService.selectFuwCarList(new FuwCar(username));
        // 定义是否存在值
        Boolean nowCarIsPer = false;
        for(FuwCar fuwCarNow:fuwCarList){
            if(fuwCarNow.getCommId().equals(fuwCar.getCommId())){
                nowCarIsPer = true;
            }
        }

        // 如果存在则不新增，并返回提示
        if(nowCarIsPer){
            return error("该商品已经加入购物车！");
        }else{
            // 新增购物车信息
            FuwCar fuwCarComm = new FuwCar();
            fuwCarComm.setPersonId(username);
            fuwCarComm.setCommId(fuwCar.getCommId());
            return toAjax(fuwCarService.insertFuwCar(fuwCarComm));
        }

    }

    /**
     * 购物车商品购买
     */
    @PreAuthorize("@ss.hasPermi('fuw:car:buyComm')")
    @Log(title = "购物车", businessType = BusinessType.OTHER)
    @PostMapping(value = "/add/addOrder")
    public AjaxResult addOrder(@RequestParam("allMoney") BigDecimal allMoney,
                           @RequestParam("carString") String carString,
                           @RequestParam("numString") String numString)
    {
        System.out.println("allMoney =" + allMoney);
        System.out.println("carString =" + carString);
        System.out.println("numString =" + numString);

        /**
         * 新增订单信息
         */
        FuwOrder fuwOrder = new FuwOrder();
        // 自定义格式UI
        String uuidStr = DataUtils.fuwUUID("Odr");
        fuwOrder.setOrderId(uuidStr);
        // 用户编号
        fuwOrder.setPersonId(getUsername());
        // 总金额
        fuwOrder.setAllMoney(allMoney);
        // 生成订单信息时间
        fuwOrder.setOrderStartTime(DateUtils.parseDate(DateUtils.getTime()));
        // 给予订单状态 （1：待付款；2：代发货；3：待收货；4：待评价；5：退换货；6：订单异常）
        fuwOrder.setOrderType("1");
        // 新增订单信息
        fuwOrderService.insertFuwOrder(fuwOrder);
        LogUtils.getBlock("订单信息" + "新增成功！");

        /**
         * 新增商品订单信息
         */
        // 拆分字符串，获取商品信息和商品数量
        String[] carStrings = carString.split(","); // 商品信息
        // 将商品数量中的undefined替换为0
        numString = numString.replaceAll("undefined", "0");
        String[] numStrings = numString.split(","); // 商品数量
        // 循环遍历新增商品订单信息
        for(int i=0; i<carStrings.length; i++){

            if(Integer.valueOf(numStrings[i]) != 0){
                // 根据commId查询对应的商品信息
                FuwComm fuwComm = fuwCommService.selectFuwCommByCommId(carStrings[i]);
                // 新建商品订单信息
                FuwCommsOrders fuwCommsOrders = new FuwCommsOrders();
                fuwCommsOrders.setOrderId(uuidStr);
                fuwCommsOrders.setCommId(carStrings[i]);
                fuwCommsOrders.setCommNum(Long.valueOf(numStrings[i]));
                fuwCommsOrders.setCommDanjia(fuwComm.getCommDanjia());
                fuwCommsOrders.setCommZhekou(fuwComm.getCommZhekou());
                // 新增商品订单
                fuwCommsOrdersService.insertFuwCommsOrders(fuwCommsOrders);
                LogUtils.getBlock("商品订单信息" + "新增成功！");

                /**
                 * 修改购物车内的信息
                 */
                FuwCar fuwCar = new FuwCar();
                fuwCar.setPersonId(getUsername());
                fuwCar.setCommId(carStrings[i]);
                fuwCarService.deleteFuwCarByFuwCar(fuwCar);
                LogUtils.getBlock("购物车信息" + "修改成功！");

                /**
                 * 修改商品库存信息
                 */
                fuwComm.setCommKucun(fuwComm.getCommKucun() - Integer.valueOf(numStrings[i]));
                fuwCommService.updateFuwComm(fuwComm);
                LogUtils.getBlock("商品信息" + "修改成功！");
            }

        }

        return AjaxResult.success("新增成功");
    }

    /**
     * 修改购物车
     */
    @PreAuthorize("@ss.hasPermi('fuw:car:edit')")
    @Log(title = "购物车", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FuwCar fuwCar)
    {
        return toAjax(fuwCarService.updateFuwCar(fuwCar));
    }

    /**
     * 删除购物车
     */
    @PreAuthorize("@ss.hasPermi('fuw:car:remove')")
    @Log(title = "购物车", businessType = BusinessType.DELETE)
	@DeleteMapping("/{uIds}")
    public AjaxResult remove(@PathVariable Long[] uIds)
    {
        return toAjax(fuwCarService.deleteFuwCarByUIds(uIds));
    }
}
